<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * 通用函数
 * 
 * @author  : $Author: spike $
 * @date    : $Date: 2014-06-16 09:30:47 +0800 (一, 2014-06-16) $
 * @version : $Id: common_helper.php 112 2014-06-16 01:30:47Z spike $
 * @rev     : $Revision: 112 $
 */
// ------------------------------------------------------------------------

/**
 * 输出 json 格式数据
 * 
 * @param   string  $msg            消息
 * @param   bool    $status         状态
 * @param   array   $data           要返回的数据
 * @param   string  $jsonp_callback jsonp
 *
 * @return  string
 */
if (!function_exists('json_exit')) 
{
    function json_exit($msg = '系统异常', $status = FALSE, $data = '', $jsonp_callback = NULL)
    {
        $result           = array();
        $result['msg']    = (string)$msg;
        $result['status'] = (bool)$status;
        $result['data']   = $data;

        $response = json_encode($result);
        !empty($jsonp_callback) && is_string($jsonp_callback) && $response = $jsonp_callback . '(' . $response . ')';
        
        header('Content-Type: application/json');
        exit($response);
    }
}

/**
 * 格式化为有符号货币单位,最多精确到分
 * @param  mixed
 * @return float
 */
if (!function_exists('moneyval')) 
{
    function moneyval($val)
    {
        return sprintf("%.2f",(float)$val);
    }
}

/**
 * 返回用户登陆信息
 * 
 * 信息完整返回数组, 否则返回FALSE
 * 
 * @return array/false 
 */
if (!function_exists('login_info')) 
{
    function login_info($key = NULL)
    {
        $admin = $_SESSION['login_info'];
        
        // 验证数据
        if( 
           ! isset($admin['admin_id'])
        OR ! isset($admin['username'])
        OR ! isset($admin['resource'])
        )
        {
            return FALSE;
        }

        if( $key === NULL)
        {
            return $admin;
        }
        else
        {
            return isset($admin[$key]) ? $admin[$key] : FALSE;
        }
    }
}

/**
 * 返回用户菜单
 * 
 * @return array
 */
if (!function_exists('menu_info')) 
{
    function menu_info()
    {
        return isset($_SESSION['login_info']['resource']['menu']) ? $_SESSION['login_info']['resource']['menu'] : array();
    }
}

/**
 * 返回面包屑
 * 
 * @return array
 */
if (!function_exists('breadcrumb')) 
{
    function breadcrumb()
    {
        return isset($_SESSION['breadcrumb']) ? $_SESSION['breadcrumb'] : array();
    }
}

/**
 * 返回当前URL
 * 
 * @return string
 */
if (!function_exists('cur_url')) 
{
    function cur_url()
    {
        $url = $_SERVER["HTTPS"] == "on" ? 'https://' : 'http://';
        if ($_SERVER["SERVER_PORT"] != "80") 
        {
            $url .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
        } 
        else 
        {
            $url .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
        }
        return $url;
    }
}

/**
 * 返回服务器环境信息
 * IP,名称,是否处于调试模式
 * 
 * @return string
 */
if (!function_exists('server_env')) 
{
    function server_env()
    {
        $server = array();
        // LOCAL_ADDR for IIS
        $server['address'] = $_SERVER['SERVER_ADDR'] ? $_SERVER['SERVER_ADDR'] : $_SERVER['LOCAL_ADDR'];
        if(strpos($server['address'], '127.') === 0)
        {
            $server['env'] = 'development';
        }
        elseif(strpos($server['address'], '192.168.0.252') === 0)
        {
            $server['env'] = 'testing';
        }
        else
        {
            $server['env'] = 'production';
        }
        $server['debug'] = defined('DEBUG') AND DEBUG === TRUE ? TRUE : FALSE;

        return $server;
    }
}

/**
 * 验证手机号格式,TRUE/FALSE
 * 
 * @return teue/false
 */
if (!function_exists('validate_mobile')) 
{
    function validate($str, $mode)
    {
        switch(strtoupper($mode)) 
        {
            case 'MOBILE':
                $pattern = '/^1[3|4|5|8]{1}\d{9}$/';
                break;

            case 'PHONE':
                $pattern = '/^((010|02[0-9]|0[3-9][0-9]{2})-)?(\d){7,9}(-\d+)?$/';
                break;

            case 'EMAIL':
                $pattern = '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/';
                break;

            case 'CHAR':
                $pattern = '/^[A-Za-z0-9\x80-\xff\']+$/';
                break;

            case 'BEAUTY_ID':    
            case 'BEAUTY_DETAIL_ID':    
            case 'COMMENT_ID':    
            case 'TREND_ID':  
            case 'CATEGORY_ID':    
            case 'ATTR_GROUP_ID':
            case 'ATTR_ID':
            case 'ATTR_VALUE_ID':
                $pattern = '/^[1-9](\d+)?$/';
                break;

            case 'BRAND_SN':
                $pattern = '/^[A-Z]{2}$/i';
                break;

            case 'GOODS_SN':
                $pattern = '/^G[0-9]{4}$/i';
                break;

            default:
                    return false;
                break;
        }
        if ( ! preg_match($pattern, $str)) 
        {
            return false;
        } 
        return true;
    }
}


/**
 * 验证字符串长度(字符数),TRUE/FALSE
 * 
 * @return true/false
 */
if (!function_exists('validate_char_length')) 
{
    function validate_length($str, $min_mength = 0, $max_length = 0)
    {
        $max_length = (int)$max_length;
        $min_mength = (int)$min_mength;
        if($max_length < $min_mength)
        {
            return false;
        }
        if(mb_strlen($str, 'UTF-8') > $max_length || mb_strlen($str, 'UTF-8') < $min_mength)
        {
            return false;
        }
        return true;
    }
}

/**
 * 输出当前时间戳  如2013-06-02 15:18:29
 * 
 * @return true/false
 */
if (!function_exists('now_str')) 
{
    function now_str()
    {
        return date("Y-m-d H:i:s");
    }
}

/**
 * 暂存数据到SESSION
 * temp('key')获取
 * temp('key', 'value')设置
 * temp('key', NULL)删除
 * 
 * @return true/false
 */
if (!function_exists('temp')) 
{
    function temp()
    {
        $num = func_num_args();
        $arg = func_get_args();
        switch ($num) 
        {
            case 1:
                    return $_SESSION[$arg[0]] ? $_SESSION[$arg[0]] : FALSE;
                break;
            case 2:
                    if($arg[1] === NULL && isset($_SESSION[$arg[0]]))
                    {
                        unset($_SESSION[$arg[0]]);
                        return TRUE;
                    }
                    else
                    {
                        $_SESSION[$arg[0]] = $arg[1];
                        return TRUE;
                    }
                break;

            default:
                    return FALSE;
                break;
        }
    }
}

/**
 * 发送http头
 */
if (!function_exists('send_header')) 
{
    function send_header($mode)
    {
        switch ($mode) 
        {
            case 'utf-8':
                    header("charset=UTF-8");
                break;

            case 'json':
                    header("Content-Type: application/json");
                break;
            
            case 'image':
                    header('Content-Type: image/jpeg');
                break;

            default:
                    
                break;
        }
    }
}

/**
 * 发送http头
 */
if (!function_exists('clean_html')) 
{
    function clean_html($str)
    {
        $str = preg_replace("/<script.*?>(\s|.)*?<\/script>/i",'',$str);
        return htmlspecialchars($str);
    }
}
/* End of file common_helper.php */